﻿<########################################################################################################
	
	.AUTHOR
		Rahul G. Babar																		 
	
	.SYNOPSYS
		Export WSPs from Solution Store
	
	.DESCRIPTION
	    Export WSPs from Solution Store
	
	.PARAMETER ExportPath
		Path on computer where solution WSPs will be exported.
		
	.PARAMETER Overwrite
		Set true to export the exising WSP again and overwrite the old one otherwise set false.
	
	.EXAMPLE
		.\ExportWSPSolutions.ps1 -ExportPath "C:\Solutions" -Overwrite $true   			 

    
########################################################################################################>

[CmdletBinding()]
Param(
   [Parameter(Mandatory=$true,Position=1)]
   [string]$ExportPath,
   [Parameter(Mandatory=$true,Position=2)]
   [bool]$Overwrite
) 

function LoadSharePointPowerShellEnvironment
{	
	write-host "Setting up PowerShell environment for SharePoint" -foregroundcolor Yellow
	write-host 
	Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
	write-host "SharePoint PowerShell Snapin loaded." -foregroundcolor Green
	write-host 
}

LoadSharePointPowerShellEnvironment

$FinalPathExists = Test-Path $ExportPath
if($FinalPathExists)
{
	$LocalFarm = Get-SPFarm -ErrorAction SilentlyContinue
	if($LocalFarm -ne $null)
	{
		$FarmSolutions = $LocalFarm.Solutions
		$Count = 0
		foreach($Solution in $FarmSolutions)
		{
			if($Solution -ne $null)
			{
				$FinalPath = $ExportPath + "\" + $Solution.Name;
				$FileExists = Test-Path $FinalPath
				if($FileExists -and -not $Overwrite)
				{
					## If file exists and user does not want to overwrite, do nothing
				}
				else
				{
					Write-Host "Exporting solution to $FinalPath..." -ForegroundColor Yellow
					Write-Host
					$Solution.SolutionFile.SaveAs($FinalPath);
					Write-Host "Exported solution to $FinalPath successfully." -ForegroundColor Green
					Write-Host
					$Count++
				}
			}
		}
		Write-Host "Exported $Count WSP Solutions to $ExportPath." -ForegroundColor Green
		Write-Host
	}
	else
	{
		Write-Error "Local SharePoint farm not found."
		Write-Host
	}	
}
else
{
	Write-Error "Path $ExportPath does not exist, please specify correct path."
	Write-Host
}

